package com.frejoys.store.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.aop.VerifyStore;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.admin.GoodsAddDto;
import com.frejoys.common.dto.admin.GoodsUpDto;
import com.frejoys.common.dto.app.GoodsIdDto;
import com.frejoys.common.dto.common.IdDto;
import com.frejoys.common.dto.common.IdPageDto;
import com.frejoys.common.dto.common.PageDto;
import com.frejoys.common.dto.store.StoreIdAndPageDto;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.response.Result;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.CommonUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.common.vo.app.StoreGoodsVo;
import com.frejoys.common.vo.store.GoodsVo;
import com.frejoys.dao.entity.Goods;
import com.frejoys.service.GoodsService;
import com.frejoys.service.StoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "商品", description = "商家端商品管理")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixStore)
@Authorization(Authority.Private)
public class MallGoodsController {

    private final GoodsService goodsService;

    private final StoreService storeService;

    private final RedissonClient redissonClient;

     @Operation(summary = "商品列表")
     @PostMapping("/goods/list")
     @Deprecated
     public Result<List<GoodsVo>> storeList(@RequestBody @Validated IdPageDto dto) {
         List<Goods> list = goodsService.getListByStoreId(dto);
         List<GoodsVo> goodsVos = BeanUtil.copyToList(list, GoodsVo.class);
         List<Integer> storeIds = goodsVos.stream().map(GoodsVo::getStoreId).collect(Collectors.toList());
         Map<Integer, String> storeIdNameMap = storeService.getIdNameMap(storeIds);
         for (GoodsVo goodsVo : goodsVos) {
             if (StrUtil.isNotEmpty(goodsVo.getCover())){
                 goodsVo.setCover(CommonUtil.getFirstCover(goodsVo.getCover()));
                 goodsVo.setFname(goodsVo.getCover());
             }
             goodsVo.setStoreName(storeIdNameMap.get(goodsVo.getStoreId()));
         }
         return Result.success(goodsVos);
     }


    @Operation(summary = "商品详情")
    @PostMapping("/goods/detail")
    public Result<StoreGoodsVo> detail(@RequestBody @Validated GoodsIdDto goodsIdDto){
        Goods goods = goodsService.getById(goodsIdDto.getId());
        StoreGoodsVo goodsVo = BeanUtil.copyProperties(goods, StoreGoodsVo.class);
        goodsVo.setFname(goodsVo.getCover());
        goodsVo.setCover(AppConfigUtil.getUrlPrefix(goodsVo.getCover()));
        return Result.success(goodsVo);
    }

    @VerifyStore
    @Operation(summary = "新增商品")
    @PostMapping("/goods/addInfo")
    public Result saveGoods(@RequestBody @Validated GoodsAddDto dto){

        RLock lock = redissonClient.getLock(CacheKeyUtil.storeGoodsLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {
                goodsService.addInfo(dto);
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }

    @VerifyStore
    @Operation(summary = "编辑商品")
    @PostMapping("/goods/upInfo")
    public Result upInfo(@RequestBody @Validated GoodsUpDto dto) {

        RLock lock = redissonClient.getLock(CacheKeyUtil.upStoreGoodsLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {
                goodsService.upInfo(dto);
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }

    @VerifyStore
    @Operation(summary = "删除商品")
    @PostMapping("/goods/delInfo")
    public Result delInfo(@RequestBody @Validated IdDto dto) {

        RLock lock = redissonClient.getLock(CacheKeyUtil.storeGoodsLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {
                goodsService.delInfo(dto.getId());
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }

    @PostMapping("/goods/storeGoodsList")
    @Operation(summary = "店铺下的商品")
    public Result<List<StoreGoodsVo>> storeGoodsList(@RequestBody @Validated StoreIdAndPageDto dto){
        return Result.success(goodsService.storeGoodsList(dto));
    }

    //商家的所有商品
    @Authorization(Authority.Protected)
    @PostMapping("/goods/goodsList")
    @Operation(summary = "商家的所有商品")
    public Result<List<StoreGoodsVo>> goodsList(@RequestBody @Validated PageDto dto) {
        return Result.success(goodsService.goodsList(dto, RequestUtil.userId()));
    }

    /**
     * 商家端-申请商品上架
     */
    @VerifyStore
    @PostMapping("/goods/up")
    @Operation(summary = "申请商品上架")
    public Result goodsUp(@RequestBody @Validated IdDto dto){

        RLock lock = redissonClient.getLock(CacheKeyUtil.storeGoodsLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {
                goodsService.goodsUp(dto);
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }

    /**
     * 商家端-申请商品下架
     */
    @VerifyStore
    @PostMapping("/goods/down")
    @Operation(summary = "商品下架")
    public Result goodsDown(@RequestBody @Validated IdDto dto){

        RLock lock = redissonClient.getLock(CacheKeyUtil.storeGoodsLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {
                goodsService.goodsDown(dto);
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }
    
}
